<template>
  <div>
    <van-action-sheet
      name="sheet"
      v-model="show"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
      @select="onSelect"
    />
    <div>{{ txt }}</div>
  </div>
</template>
<script>
// import { Dialog } from "vant";
import * as imageConversion from "image-conversion";
import { loadJS } from "@/utils/index";
import { uploadImage } from "@/api/qy";
export default {
  name: "appUpload",
  data() {
    return {
      indexNum: 0,
      show: false,
      actions: [{ name: "拍照" }, { name: "从相册选择" }],
      backUrl: false,
      validatInfo: {},
      txt:'',
      isHead: false,
      is_more: 0
    };
  },
  mounted() {
    loadJS(
      `https://api.onestep6.com/resource/js/zdjs.bridge.min.js?t=${Date.now()}`
    ).then(() => {
      console.log("zdjs.bridge.min.js loaded!");
    });
  },
  methods: {
    onCancel() {
      this.show = false;
    },
    onSelect(item) {
      console.log(item.name);
      if (item.name == "拍照") {
        this.openNativeCamera();
      }
      if (item.name == "从相册选择") {
        this.openNativePhotos();
      }
    },
    // 调用原生拍照方法
    openNativeCamera() {
        let that = this;
      // 参数:quality 压缩质量 isCrop 是否裁剪
      var m = {
        quality: 30,
        isCrop: true,
        needBase64: true,
        isHead: that.isHead
      };
      // 返回base64
      window.callHandler("flutterOpenCamera", m, function(data) {
        let baseStr = '';
          if (data.indexOf('/9j') != -1) {
            baseStr = 'data:image/jpeg;base64,'+data;
          }else if (data.indexOf('iVB') != -1) {
            baseStr = 'data:image/png;base64,'+data;
          } else{
            this.$toast("上传头像图片只能是JPG或PNG格式");
            return false
          }
          baseStr = baseStr.replace(/"/g,'')
          // that.$emit("showImg",baseStr)
          // Dialog.alert({
          //   title: '数据',
          //   message: `${baseStr}`,
          // }).then(() => {
            
          // });
          if (that.backUrl) {
              that.upImg(baseStr);
          } else {
              that.$emit("setImg", baseStr, that.indexNum);
          }
      })
    },
    //调用原生相册方法 !!!!!!!!!!!!!!!!相册放回的是个数组！！！！！！！！！！
    openNativePhotos() {
        let that = this;
      // 参数:quality 压缩质量 iscrop 是否裁剪
      // maximumImagescount 图片数量 最大值9 最小值1
      var m = {
        quality: 30,
        isCrop: true,
        maximumImagesCount: 1,
        needBase64: true,
        isHead: that.isHead
      };
      if (that.is_more) {
        m.maximumImagesCount = that.is_more;
      }
      // 返回base64
      window.callHandler("flutterImagePicker", m, function(dataList) {
          let data = dataList.replace(/\[|\]|"/g, '')
          // Dialog.alert({
          //   title: '数据',
          //   message: `${data}`,
          // }).then(() => {
            
          // });
          let baseStr = '';
          if (data.indexOf('/9j') != -1) {
            baseStr = 'data:image/jpeg;base64,'+data;
          }else if (data.indexOf('iVB') != -1) {
            baseStr = 'data:image/png;base64,'+data;
          } else{
            this.$toast("上传头像图片只能是JPG或PNG格式");
            return false
          }
          baseStr = baseStr.replace(/"/g,'')
          // that.$emit("showImg",baseStr)
          
          if (that.backUrl) {
              that.upImg(baseStr);
          } else {
              that.$emit("setImg", baseStr, that.indexNum);
          }
      });
    },
    // getType(data) {
      // if (data.indexOf('/9j') != -1) {
      //   return data = 'data:image/jpeg;base64,'+data;
      // }else if (data.indexOf('iVB') != -1) {
      //   return data = 'data:image/png;base64,'+data;
      // } else{
      //   this.$toast("上传头像图片只能是JPG或PNG格式");
      //   return false
      // }
    // },
    // 需要上传返回图片地址
    upImg(base64Data) {
      let type = base64Data.split(";")[0].split(":")[1];
      let name = "";
      if (type == "image/png") {
        name = "imgName.png";
      } else {
        name = "imgName.jpg";
        type = "image/jpeg";
      }
      let file = this.base64ToFile(base64Data, name, type);
      this.upFile(file);
    },
    async upFile(file) {
      let that = this;
      let form = new FormData();
      // 压缩图片功能
      form.append("file", await this.beforeAvatarUpload(file), file.name);
      uploadImage(form, this.validatInfo).then(res => {
        if (res.status === 1) {
          that.$emit("setUrl", res.data.uri, this.indexNum);
        } else {
          that.$toast.fail("图片上传失败，请重新上传");
        }
      });
    },
    //将base64转换为File
    base64ToFile(base64Data, fileName, mimeType) {
      // 将base64字符串转换为二进制数据
      const byteString = atob(base64Data.split(",")[1]);
      const mimeString = mimeType || "application/octet-stream";
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      // 使用Blob对象将二进制数据封装起来
      const blob = new Blob([ab], { type: mimeString });
      // 使用File构造函数将Blob对象转换为File对象
      const file = new File([blob], fileName, {
        type: mimeString,
        lastModified: Date.now()
      });
      return file;
    },
    // 压缩图片
    beforeAvatarUpload(file) {
      console.log(file);
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      // const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJpgOrPng) {
        this.$toast("上传头像图片只能是JPG或PNG格式");
        return false;
      }
      // if (!isLt2M) {
      //     this.$toast('上传头像图片大小不能超过1MB')
      //     return false
      // }
      return new Promise(resolve => {
        // 压缩到100KB,这里的100就是要压缩的大小，可自定义
        imageConversion.compressAccurately(file, 1000).then(res => {
          console.log(res);
          resolve(res);
        });
      });
    },
    copyText(txt) {
        // 使用Clipboard API
        if (navigator.clipboard) {
            navigator.clipboard.writeText(txt).then(() => {
                this.$toast.success('复制成功！');
            }).catch(err => {
                console.error("复制失败:", err);
                this.$toast.fail("复制失败:"+err);
                this.fallbackCopyText(); // 如果Clipboard API失败，使用回退方案
            });
        } else {
            // Clipboard API不可用，使用回退方案
            this.fallbackCopyText(txt);
        }
    },
    fallbackCopyText(txt) {
        // 创建临时的textarea元素
        const tempTextArea = document.createElement("textarea");
        tempTextArea.value = txt;
        // 防止页面布局被临时元素影响
        tempTextArea.style.position = "fixed"; // 固定在视口
        tempTextArea.style.left = "-9999px"; // 隐藏到视口外
        // 将textarea添加到body中
        document.body.appendChild(tempTextArea);
        // 选择文本
        tempTextArea.select();
        // 执行复制操作
        try {
            const successful = document.execCommand("copy");
            const msg = successful ? "successful" : "unsuccessful";
            console.log("Fallback: Copying text command was " + msg);
            this.$toast.success("复制成功");
        } catch (err) {
            console.error("Fallback: Oops, unable to copy", err);
            this.$toast.fail("复制失败");
        }
        // 移除临时元素
        document.body.removeChild(tempTextArea);
    }
  }
};
</script>
<style lang="less" scoped>
div {
  box-sizing: border-box;
}
</style>
